const moment = require('moment');

let TEST = false
//TEST = true

module.exports = function (app, opts) {
    const abnormalRateTrend = app.fs.scheduleInit(
        {
            interval: '0 45 14 * * *',//次日零点
            immediate: TEST,
            proRun: !TEST,
        },
        async () => {
            try {
                const { models } = app.fs.dc;
                let inspectedList = await models.UnplannedPatrolRecord.findAll({//检修记录
                    where: { alarm: true },
                    attributes: ['id', 'planId'],
                    include: [{
                        model: models.UnplannedRecordTemplates,
                        where: { alarm: true },
                        attributes: ['id', 'templateId'],
                        include: [{
                            model: models.UnplannedRecordCheckItems,
                            where: { alarm: true },
                            attributes: ['id', 'checkItemId']
                        }]
                    }]
                })


                let plans = await models.UnplannedPatrolPlan.findAll({
                    where: { status: 2 },
                    attributes: ['id', 'name', 'industryTypeId'],
                    include: [{
                        // required: false,
                        model: models.UnplannedPatrolTemplate,
                        as: 'ttemplates',
                        attributes: ['id', 'name'],
                        where: { workType: 2 },
                        include: [{
                            model: models.UnplannedCheckItems,
                            required: false,
                        }]
                    }]
                });
                let statisticsByIndustry = [];
                for (let i = 0; i < plans.length; i++) {
                    let plan = plans[i].dataValues;
                    if (plan.industryTypeId) {
                        let planItemsCount = 0;//检查项个数
                        let abnormalItemsCount = 0;//异常检查项个数

                        let inspected = inspectedList.find(dl => dl.dataValues.planId === plan.id);//检修记录

                        //step1 统计检查项个数
                        //自动过期的 取配置总数; 有记录的取points中检查项总数

                        //step2 统计异常 个数
                        //if (inspected) {
                        for (let k = 0; k < inspected.unplannedRecordTemplates.length; k++) {
                            abnormalItemsCount += inspected.unplannedRecordTemplates[k].dataValues.unplannedRecordCheckItems.length;
                            //planItemsCount += points.length;
                            // for (let m = 0; m < points.length; m++) {
                            //     let point = points[m];
                            //     if (point.result === 'abnormal') {//异常
                            //         abnormalItemsCount++;
                            //     }
                            // }
                        }
                        //} else {
                        for (let j = 0; j < plan.ttemplates.length; j++) {
                            planItemsCount += plan.ttemplates[j].dataValues.unplannedCheckItems.length;
                        }
                        //}

                        //step3 按行业分组
                        let ext = statisticsByIndustry.find(sbi => sbi.industryTypeId === plan.industryTypeId);
                        if (ext) {//已有
                            ext.planItemsCount += planItemsCount;
                            ext.abnormalItemsCount += abnormalItemsCount;
                        } else {
                            let obj = {
                                industryTypeId: plan.industryTypeId,
                                planItemsCount,//某任务下检查项总数
                                abnormalItemsCount,////某任务下异常检查项总数
                                date: moment().add(-1, 'day').format("YYYY-MM-DD")
                            }
                            statisticsByIndustry.push(obj);
                        }

                    }
                }

                statisticsByIndustry.forEach(pl => {
                    let r = pl.planItemsCount ? parseFloat((100 * pl.abnormalItemsCount / pl.planItemsCount).toFixed(2)) : 0
                    pl.rate = Math.min(r, 100)
                })
                //入库
                await models.AbnormalStatisticsByIndustry.bulkCreate(statisticsByIndustry);
                await models.AbnormalStatisticsByIndustry.destroy({//存半年的数据
                    where: { date: { $lt: moment().add(-6, 'month').startOf('day').format('YYYY-MM-DD HH:mm:ss') } }
                });
            } catch (error) {
                app.fs.logger.error(`sechedule: abnormalRateTrend, error: ${error}`);
            }
        }
    );

    return {
        abnormalRateTrend
    }
}